#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCamera>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->widget->resize(600, 400);

    camera = new QCamera();
    QCameraViewfinder *view_finder = new QCameraViewfinder();
    camera_image_capture = new QCameraImageCapture(camera);
    capture_button = new QPushButton();
    save_button = new QPushButton();
    exit_button = new QPushButton();
    display_label = new QLabel();

    QHBoxLayout *main_layout = new QHBoxLayout();
    QVBoxLayout *v_layout = new QVBoxLayout();

    display_label->setFixedSize(150, 150);
    display_label->setScaledContents(true);

    v_layout->addWidget(display_label);
    v_layout->addStretch();
    v_layout->addWidget(capture_button);
    v_layout->addWidget(save_button);
    v_layout->addWidget(exit_button);

    main_layout->addWidget(view_finder);
    main_layout->addLayout(v_layout);

    connect(capture_button, &QPushButton::clicked, this, &MainWindow::captureImage);
    connect(save_button, &QPushButton::clicked, this, &MainWindow::saveImage);
    connect(exit_button, &QPushButton::clicked, this, &MainWindow::close);
    connect(camera_image_capture, &QCameraImageCapture::imageCaptured, this, &MainWindow::displayImage);

    camera_image_capture->setCaptureDestination(QCameraImageCapture::CaptureToFile);
    camera->setCaptureMode(QCamera::CaptureStillImage);
    camera->setViewfinder(view_finder);
    camera->start(); //启动摄像头

    ui->widget->setLayout(main_layout);
    translateLanguage();
}

MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::translateLanguage()
{

    capture_button->setText(tr("capture"));
    save_button->setText(tr("save"));
    exit_button->setText(tr("exit"));
}

void MainWindow::displayImage(int id, QImage image)
{
    display_label->setPixmap(QPixmap::fromImage(image));
}

void MainWindow::captureImage()
{
    //截图
    camera_image_capture->capture();
}

void MainWindow::saveImage()
{
    const QPixmap *pixmap = display_label->pixmap();
    if(pixmap)
    {
        pixmap->save("F:\\a.jpg");
    }
}
